package com.domain;

import com.tcp.TcpMessageSenderInterceptor;
import com.tcp.TcpStateChecker;
import org.jetlinks.core.ProtocolSupport;
import org.jetlinks.core.defaults.CompositeProtocolSupport;
import org.jetlinks.core.device.session.DeviceSessionManager;
import org.jetlinks.core.message.codec.DefaultTransport;
import org.jetlinks.core.metadata.DefaultConfigMetadata;
import org.jetlinks.core.metadata.types.IntType;
import org.jetlinks.core.metadata.types.StringType;
import org.jetlinks.core.spi.ProtocolSupportProvider;
import org.jetlinks.core.spi.ServiceContext;
import org.jetlinks.supports.official.JetLinksDeviceMetadataCodec;
import org.jetlinks.supports.server.DecodedClientMessageHandler;
import reactor.core.publisher.Mono;

public class MyProtocolSupportProvider implements ProtocolSupportProvider {

    //下一步调config模板配置
    private static final DefaultConfigMetadata config = new DefaultConfigMetadata(
            "tcp请求配置"
            , "")
            .add("host", "设备地址", "设备IP地址XXX.XXX.XXX.XXX", new StringType())
        .add("port", "端口号", "设备端口号", new IntType());



    @Override
    public Mono<? extends ProtocolSupport> create(ServiceContext context) {
        CompositeProtocolSupport support = new CompositeProtocolSupport();
        support.setId("tcp-vertx");
        support.setName("tcp主动获取设备数据");
        support.setDescription("tcp主动获取设备数据");
        support.setMetadataCodec(new JetLinksDeviceMetadataCodec());
        support.addConfigMetadata(DefaultTransport.TCP, config);

        return Mono.zip(
                        Mono.justOrEmpty(context.getService(DecodedClientMessageHandler.class)),
                        Mono.justOrEmpty(context.getService(DeviceSessionManager.class))
                )
                .map(tp2 -> {
                    support.setDeviceStateChecker(new TcpStateChecker(tp2.getT1(), tp2.getT2()));
                    return new TcpMessageSenderInterceptor(tp2.getT2());
                })
                .doOnNext(interceptor -> {
                    support.addMessageSenderInterceptor(interceptor);
                })
                .thenReturn(support);

    }
}
